package cate.common.table.area;

import cate.common.table.ESheet;
import cate.common.util.XT;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/** 地区 */
public class AreaCitySheet extends ESheet<AreaCityRow> {
    private final Map<Integer, List<AreaCityRow>> provinceCitys = new ConcurrentHashMap<>();

    @Override
    public String getSheetName() {
        return "地区";
    }

    @Override
    protected AreaCityRow buildRow() {
        return new AreaCityRow();
    }

    @Override
    public void decode() {
        super.decode();
        initProvinceCitys();
    }

    private void initProvinceCitys() {
        if (provinceCitys.isEmpty()) {
            synchronized (provinceCitys) {
                if (provinceCitys.isEmpty()) {
                    for (AreaCityRow areaCityRow : getList()) {
                        provinceCitys.computeIfAbsent(
                                areaCityRow.belongCode, key -> new ArrayList<>());
                        provinceCitys.get(areaCityRow.belongCode).add(areaCityRow);
                    }
                }
            }
        }
    }


    public int random(int provinceCode){
        List<AreaCityRow> areaCityRows = provinceCitys.get(provinceCode);
        if(areaCityRows==null||areaCityRows.isEmpty()){
            return 0;
        }
        return areaCityRows.get(XT.randomIndex(areaCityRows.size())).code;
    }
}
